<?php

namespace App\Http\Controllers\Api;

use App\Models\Config;
use App\Models\Gift;
use App\Models\GivedGift;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Resources\Gift as GiftCollection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class GiftsController extends ApiController
{


    public function __construct()
    {
        $this->middleware('auth:api')->only([
            'sendGift'
        ]);
    }

    /**
     *
     * @api {get} /gifts 获取所有的礼物
     * @apiName Get all gifts types
     * @apiGroup Gift
     *
     * @apiVersion 1.0.0
     * @apiSampleRequest /api/gifts
     *
     */
    public function index(){

        $gifts = Gift::all();

        return GiftCollection::collection($gifts);

    }

    /**
     *
     *
     * @api {post} /gifts/send 送礼
     * @apiName SendGift
     * @apiGroup Gift
     *
     * @apiParam {Int} gift_id 要送礼物的id.
     * @apiParam {Int} to_user_id 要送给用户的id.
     * @apiParam {String} token 送礼用户的token.
     * @apiParam {Int} send_count 送礼数量（默认不传为1）.
     * @apiParam {Int} type 0=>不关联 1=>关联吧 2=>关联书籍.
     * @apiParam {Int} relation 关联书籍贴吧的编号.
     *
     * @apiVersion 1.0.0
     *
     * @apiSampleRequest /api/gifts
     */
    public function sendGift(Request $request){

        $this->validate($request,[
            'gift_id' => 'required|exists:gift,id',
            'to_user_id' => 'required|exists:user,id',
            'type' => 'required',
            'relation' => '',
            'send_count' => ''
        ]);


        $gift_id = $request->gift_id;

        $gift = Gift::find($gift_id);

        $to_user_id = $request->to_user_id;

        $to_user = User::find($to_user_id);


        $sendCount = $request->get('send_count') ?: 1;


        $type = $request->get('type') ?: 0;
        $relation = $request->get('relation');


        $sendUser = Auth::user();

        if ($sendCount <= 0){
            return $this->failed('送礼数量不符合要求');
        }


        if (! $sendUser->canSendGift($gift,$sendCount)){
            // 无法送礼
            return $this->failed('余额不足');
        }

        // 送礼
        DB::beginTransaction();

        try {

            $realMoney = 0;

            if ($gift_id == 1){

                $sendUser->flowers -= $sendCount;


            }else{

                $coin = $gift->price * $sendCount;

                $sendUser->ys_coin -= $coin;


                $userGet = 0.5;


                $config = Config::first();


                if ($config){

                    $bonus = $config->bonus;

                    if ($bonus >= 0 && $bonus <= 10){
                        $userGet = (10 - $bonus) / 10;
                    }
                }


                $realMoney = $coin * 0.1 * $userGet;
                $to_user->money += $realMoney;

                $sendUser->grade += $coin;

            }



            GivedGift::create([
                'gift_id' => $gift->id,
                'gifts_time' => time(),
                'uid' => $sendUser->id,
                'gifts_uid' => $to_user->id,
                'counts' => $sendCount,
                'type' => $type,
                'relation' => $relation,
                'real_money' => $realMoney
            ]);

            $sendUser->save();
            $to_user->save();

            DB::commit();
            $success = true;
        } catch (\Exception $e) {
            $success = false;
            DB::rollback();
        }
        if ($success) {
            return $this->message('送礼成功',1);
        }

        return $this->failed('送礼失败');



    }


}
